package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**
     * 定义socket监听的端口号
     */
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    private String webAppUrl = "/Users/webapps";

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        // 加载解析相关的配置，web.xml
        loadJar();
        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
        System.out.println("=========>>>>>>使用线程池进行多线程改造");
/*
            多线程改造（使用线程池）
         */

        while(true) {
            System.out.println("232");
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }


    }


    private Map<String, Class> servletMap = new HashMap<String, Class>();


    private void loadJar() throws IOException, ClassNotFoundException {
        File file = new File(webAppUrl);
        File[] files = file.listFiles();
        if (files != null) {
            for (File fileItem : files) {
                String fileName = fileItem.getName();
                int i = fileName.lastIndexOf(".jar");
                if(i<0){
                    i = 1;
                }
                String filePrefix = fileName.substring(0,i);
                if (fileName.endsWith(".jar")) {
                    URLClassLoader classLoader = new URLClassLoader(new URL[]{new URL("file:"+webAppUrl+"/"+fileName)}, Thread.currentThread().getContextClassLoader());
                    loadServlet(classLoader, filePrefix);
                }
            }

        } else {
            System.out.println("未部署项目到" + webAppUrl);
        }

    }

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet(URLClassLoader classLoader, String filePrefix) {
        InputStream resourceAsStream = classLoader.getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                System.out.println(servletClass);

                servletMap.put("/"+filePrefix + urlPattern, classLoader.loadClass(servletClass));
                System.out.println("/"+filePrefix + urlPattern);
            }
        } catch (DocumentException | ClassNotFoundException e) {
            e.printStackTrace();
        }

    }


    /**
     * Minicat 的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
